package spring.DI;

import com.me.common.util.SleepUtil;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.Map;

/**
 * 
 *
 * @author ME
 */
@Service
public class IndexService implements InitializingBean {

    @Autowired
    private Map<String, IndexDao> indexDaoMap;

    @Autowired
    // @Qualifier("indexDaoImpl1")
    private IndexDao indexDaoImpl2;// 变量名改为 indexDao，则根据名称找不到 Bean 会报错

    // 属性注入（@Autowired、@Resource）下 setter方法 非必须
    // public void setDao(IndexDaoImpl dao) {
    //     this.indexDaoImpl2 = dao;
    // }

    /**
     * TODO 在 IndexDaoImpl2 的构造方法中睡眠 3s, 而 @PostConstruct标注的方法中开启的线程并没有提前打印,
     *  说明是在所有 Bean初始化完成之后才触发的
     */
    @PostConstruct
    public void postConstruct() {
        System.out.println("indexService PostConstruct：" + indexDaoMap);
        new Thread(() -> {
            for (int i = 1; i <= 3; i++) {
                System.out.println("IndexService-sub-thread print: " + i);
                SleepUtil.seconds(1);
            }
        }).start();
    }

    @Override
    public void afterPropertiesSet() {
        System.out.println("indexService InitializingBean#afterPropertiesSet: ");
        System.out.println("IndexService hashCode: " + this.hashCode());
    }

    @PreDestroy
    public void destroy() {
        System.out.println("bye bye!");
    }

    public void service() {
        System.out.println("indexService.service()");
        indexDaoImpl2.test();
    }
}
